<template>
    <Dialog :app-dialog="appDialog">
        <el-form ref="formRef" :model="groupData" :rules="rules" label-width="auto" class="demo_dynamic">
            <el-form-item prop="group_title" label="标签组名称：">
                <el-input
                    v-model="groupData.group_title"
                    placeholder="请输入标签组名"
                    show-word-limit
                    maxlength="15"
                    @input="e => (groupData.group_title = special(e))"></el-input>
            </el-form-item>
            <el-form-item class="tag_group" prop="group_type" label="标签组类别：">
                <el-select
                    v-model="groupData.group_type"
                    filterable
                    default-first-option
                    placeholder="请选择所属标签组类别">
                    <el-option
                        v-for="item in tagsData"
                        :key="item.id"
                        :label="item.name"
                        :value="item.name"
                        :disabled="item.list_type == 2">
                        <el-tooltip
                            effect="dark"
                            placement="top"
                            popper-class="tool-tip"
                            :disabled="item.list_type != 2">
                            <template #content> AI外呼标签类别仅用于同步外呼系统<br />标签，不支持创建。 </template>
                            <span style="float: left">{{ item.name }}</span>
                        </el-tooltip>
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item
                class="tag_group"
                prop="tags"
                label="标签："
                :rules="{ required: true, message: '标签不能为空', trigger: 'blur' }">
                <span v-for="(k, index) in tags" :key="index" class="zw-el-tags">
                    <editInput
                        v-if="k.isEdit"
                        ref="editInpt"
                        :tag="k"
                        @editedTag="editedTag"
                        @loseBlur="loseBlur"></editInput>
                    <el-tag
                        v-else
                        :effect="k.sys_qy_tag_group == 1 ? 'light' : 'plain'"
                        :type="k.sys_qy_tag_group == 1 ? 'info' : ''"
                        :closable="k.sys_qy_tag_group == 1 ? false : true"
                        @close="handleClose(k)"
                        @dblclick="handleEdit(k, index)">
                        <el-tooltip
                            effect="dark"
                            placement="top"
                            popper-class="tool-tip"
                            :disabled="k.sys_qy_tag_group != 1">
                            <template #content>
                                该标签是企微后台创建的，不支持编辑/<br />删除，请至企微后台操作。
                            </template>
                            {{ k.name }}
                        </el-tooltip>
                    </el-tag>
                </span>
                <el-input
                    v-if="inputVisible"
                    ref="InputRef"
                    v-model="inputValue"
                    placeholder="请输入标签内容"
                    class="create_label_input"
                    maxlength="15"
                    style="width: 8.125rem"
                    @keyup.enter="handleInputConfirm"
                    @blur="handleInputConfirm">
                </el-input>
                <el-button v-else plan :icon="Plus" class="button-new-tag ml-1" @click="createLabel">
                    添加标签
                </el-button>
            </el-form-item>
        </el-form>
    </Dialog>
    <abnormalDialog ref="abnormalDialogRef"></abnormalDialog>
</template>
<script setup lang="ts">
import { ref, reactive, nextTick, watch } from 'vue';
import Dialog from './Dialog.vue';
import editInput from './editInput.vue';
import abnormalDialog from './abnormalDialog.vue';
import { ElInput, ElForm, ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { editTagGroup, addTags, getTagsList } from '@/api/customerCenter';
import { getSetionId } from '@/utils/utils';
import lodash from 'lodash';

const InputRef = ref<InstanceType<typeof ElInput>>();
const formRef = ref<InstanceType<typeof ElForm>>();
const editInpt = ref<InstanceType<typeof ElForm>>();
const abnormalDialogRef = ref<InstanceType<typeof ElForm>>();

const emit = defineEmits(['submit']);

const inputValue = ref('');
const inputVisible = ref(false);
const isEdit = ref(false);
const isRepeat = ref(false); // 标签是否重复
const tagsData = ref([]); // 标签组类别列表
// 自定义校验标签
const validateTag = (rule: any, value: any, callback: any) => {
    if (!value || tags.value.length == 0) {
        callback(new Error('标签不能为空'));
    } else if (isRepeat.value) {
        callback(new Error('标签名不能重复'));
    } else {
        callback();
    }
};
// 表单校验
const rules = reactive({
    group_title: [{ required: true, message: '标签组名称不能为空', trigger: 'change' }],
    group_type: [{ required: true, message: '标签组类别不能为空', trigger: 'change' }],
    tags: [{ validator: validateTag, trigger: 'blur' }]
});
const cancelHandel = () => {
    appDialog.visible = false;
    formRef.value.resetFields();
    isEdit.value = false;
    isRepeat.value = false;
    groupData.group_title = '';
    groupData.group_type = '';
    tags.value = [];
    groupData.tags = [];
    groupData.update_tags = [];
    groupData.edit_tags = [];
    inputValue.value = '';
    emit('submit');
};
// 保存标签
const submitHandel = () => {
    formRef.value.validate(async (valid: any) => {
        if (valid) {
            const addTag = tags.value.filter((item: any) => !item.id);
            let params = {};
            if (isEdit.value) {
                params = {
                    group_title: groupData.group_title,
                    group_type: groupData.group_type,
                    tags: getSetionId('name', addTag), //新增的标签内容
                    update_tags: groupData.update_tags, //删除的标签id
                    edit_tag: groupData.edit_tags, //编辑的标签
                    group_id: groupData.group_id
                };
            } else {
                params = {
                    group_title: groupData.group_title,
                    group_type: groupData.group_type,
                    tags: getSetionId('name', tags.value)
                };
            }
            try {
                isEdit.value ? await editTagGroup(params) : await addTags(params);
                ElMessage.success(`${isEdit.value ? '编辑' : '新建'}标签组成功`);
                cancelHandel();
            } catch (e) {
                if (e?.code == 51042) {
                    cancelHandel();
                    abnormalDialogRef.value.openAbnormal();
                }
            }
        }
    });
};
// 标签类型
const getTagsListFun = () => {
    inputVisible.value = false;
    isRepeat.value = false;
    getTagsList().then((r: any) => {
        tagsData.value = r;
    });
};

// 特殊字符输入
const special = (val: any) => {
    val = val
        .replace(/[`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g, '')
        .replace(/\s/g, '');
    return val;
};
const appDialog = reactive({
    visible: false,
    title: `新建标签组`,
    width: '35rem',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '保存'
});
// 编辑标签
const handleEdit = (val: any, index: any) => {
    if (val.create_type == 2) {
        return;
    }
    val.isEdit = true;
    nextTick(() => {
        editInpt.value[editInpt.value.length - 1]?.inputFouse();
    });
};
// 新建分组
const groupData = reactive({
    group_title: '',
    group_type: '',
    tags: [],
    update_tags: [],
    edit_tags: [],
    group_id: ''
});
const tags = ref([]);
const handleClose = (tag: any) => {
    if (tag.create_type == 2) {
        return;
    }
    if (tag?.id) {
        groupData.update_tags.push(tag?.id);
    }
    if (groupData.edit_tags.length > 0) {
        groupData.edit_tags = groupData.edit_tags.filter((item: any) => item.id !== tag.id);
    }
    tags.value = tags.value.filter((item: any) => item.name !== tag.name);
    groupData.tags = groupData.tags.filter((item: any) => item !== tag.name);
};
const createLabel = () => {
    if (!isRepeat.value) {
        inputVisible.value = true;
        nextTick(() => {
            InputRef.value?.input?.focus();
        });
    }
};
const handleInputConfirm = () => {
    isRepeat.value = false;
    formRef.value.clearValidate('tags');
    if (tags.value.length > 3000) {
        ElMessage.warning('标签最多创建3000个');
        return;
    }
    if (inputValue.value) {
        if (groupData.tags.includes(inputValue.value)) {
            isRepeat.value = true;
            formRef.value.validateField('tags');
            return;
        }
        tags.value.push({ name: inputValue.value });
        groupData.tags.push(inputValue.value);
    } else {
        inputVisible.value = false;
    }
    inputValue.value = '';
};
// 获取修改后的标签
const editedTag = (val: any) => {
    isRepeat.value = false;
    formRef.value.clearValidate('tags');
    const isSame = groupData.edit_tags.some((item: any) => {
        return val.name == item.name;
    });
    if (!groupData.tags.includes(val.name) && val.name && !isSame) {
        val.isEdit = false;
        if (val.id) {
            groupData.edit_tags.push({
                id: val.id,
                name: val.name
            });
        }
    } else {
        isRepeat.value = true;
        formRef.value.validateField('tags');
        return;
    }
};
const arr = ref([]);
//编辑失去焦点
const loseBlur = (val: any) => {
    arr.value.forEach((it: any) => {
        if (val.id == it.id && val.name == it.name) {
            val.isEdit = false;
            isRepeat.value = false;
            formRef.value.clearValidate('tags');
            return;
        }
    });
    val.isEdit = isRepeat.value;
};
// 数据回显
const echo = (data: any) => {
    isEdit.value = true;
    groupData.group_id = data.group_id;
    groupData.group_title = data.group_name;
    groupData.group_type = data.group_type_value;
    groupData.tags = getSetionId('name', data.tags);
    tags.value = lodash.cloneDeep(data.tags);
    arr.value = lodash.cloneDeep(data.tags);
    tags.value.map((item: any) => {
        item.isEdit = false;
    });
};
watch(
    () => appDialog.visible,
    val => {
        if (val) {
            getTagsListFun();
        }
    }
);
defineExpose({
    appDialog,
    groupData,
    isEdit,
    echo
});
</script>
<style lang="scss" scoped>
.demo_dynamic {
    margin-top: 14px;
    .create_label_input {
        width: 140px;
    }
    .mr15 {
        margin-right: 0.9375rem;
    }
}
.zw-el-tags {
    margin-right: 6px;
}
.tool-tip {
    width: 200px;
}
</style>
